package Heap.LeetCode;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * 出现次数最高的k个元素
 */
public class Num347 {
    private class Freq implements Comparable<Freq> {
        int key;
        int times;

        public Freq(int key, int times) {
            this.key = key;
            this.times = times;
        }

        @Override
        public int compareTo(Freq o) {
            return this.times - o.times;
        }
    }

    public int[] topKFrequent(int[] nums, int k) {
        int[] ret = new int[k];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        Queue<Freq> queue = new PriorityQueue<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (queue.size() < k) {
                queue.offer(new Freq(entry.getKey(), entry.getValue()));
            } else {
                Freq freq = queue.peek();
                if (entry.getValue() < freq.times) {
                    continue;
                } else {
                    queue.poll();
                    queue.offer(new Freq(entry.getKey(), entry.getValue()));
                }
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = queue.poll().key;
        }
        return ret;
    }
}
